import PageBody from '@/components/school/pageBody';

const app = getApp();
import diyJson from '@/config/diy.js';
import {BASE_CONFIG} from "@/config/app";
import {mapGetters} from "vuex";
import OrderList from '@/components/school/orderList';
import * as OrderApi from '@/api/school/order.js';

export const mixins = {
  components: {
    PageBody, OrderList
  }
  , computed: mapGetters(['userInfo', 'schoolId', 'isLogin'])
  , data() {
    return {
      socketStateMsg: '连接中...',
      themConfig: diyJson.commonStyle,
      tagStyle: {
        img: 'width:100%;display:block;',
        table: 'width:100%',
        video: 'width:100%'
      }

      // 聊天框输入内容距离顶部
      , scrollTop: 0

      , showLoading: true

      //1=文本消息，2=图片，3=富文本消息,4=订单消息
      , chatMsgList: []

      , pageBody: {
        background: 'white',
        // #ifdef MP
        pageHeight: '100%',
        // #endif
        // #ifdef H5
        pageHeight: app.globalData.windows.pageBody - 70,
        // #endif

        orderInfo: undefined
      },

      sockectClient: undefined,
      chatInputMsg: '',
      errorMsg: '',
      socketOpen: false,
      urlParams:{},

      // 消息发送模版
      msgTemplate: {
        // message为消息主体
        "message": '', // 发送消息的会员
        "memberInfo": {
          "memberName": "接单员",
          "memberId": "1002",
          "memberAvatar": "http://127.0.0.1"
        },
        // 消息类型：1=文本消息，2=图片，3=富文本消息,4=订单消息
        "msgType": 1,
        // 聊天类型：订单/客服【当前是客服 写死即可】
        "chatType": "ORDER",
        "groupId": "",
        "header": {
          "tenantId": undefined, "schoolId": undefined, "token": ""
        }
      }
    }
  }
  , onShow() {
    console.log("websocketUrl", BASE_CONFIG.websocketUrl);

    /**
     * 获取进入携带参数
     * {
     *   "groupId":"476564653",
     *   "chatType":"ORDER" // CUSTOMER
     *   "refId":"CUSTOMER" // 或者订单ID 如果是订单的话需要传递
     *   "orderInfo":{
     *     "orderNo",
     *     "memberIds":""
     *   }
     * }
     */
    let data = this.getUrlParams();
    this.urlParams = data;

    // 初始化会员消息
    this.initMsmTemplate(data);
    if (!this.socketOpen) {
      this.initWebSocket(data);
    }
  },
  mounted() {
  },
  methods: {

    /**
     *
     * {
     *   "groupId":"",
     *   "chatType":"ORDER" // CUSTOMER
     *   "refId":"CUSTOMER" // 或者订单ID 如果是订单的话需要传递
     *   "orderInfo":{
     *     "orderNo",
     *     "memberIds":""
     *   }
     * }
     * @returns {*|(function(*): *)|{}}
     */
    getUrlParams() {
      let data = this.$store.state.app.jumpParams;
      console.log("jumpParams", data)
      if (data != null) {
        if (typeof data === 'string') {
          data = JSON.parse(data)
        }
        return data;
      }
      return {};
    },

    // 初始化消息模版
    initMsmTemplate(data) {
      this.msgTemplate.memberInfo.memberId = this.userInfo.id;
      this.msgTemplate.memberInfo.memberName = this.userInfo.nickName;
      this.msgTemplate.memberInfo.memberAvatar = this.userInfo.avatar;
      this.msgTemplate.chatType = data.chatType;
      this.msgTemplate.header.tenantId = BASE_CONFIG.tenantId;
      this.msgTemplate.header.schoolId = this.schoolId;
      this.msgTemplate.header.token = this.$store.state.app.token;
      this.msgTemplate.groupId = data.groupId
    },

    // 打开连接
    async initWebSocket(data) {
      let that = this;
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
        uni.showToast({
          title: "您的浏览器不支持WebSocket"
        })
      } else {

        // 'ws://127.0.0.1:39307/{userId}/{refId}/{chatType}/{tenantId}',
        let url = BASE_CONFIG.websocketUrl;
        url = url.replace("{userId}", this.userInfo.id)
            .replace("{refId}", data.refId)
            .replace("{chatType}", data.chatType)
            .replace("{tenantId}", BASE_CONFIG.tenantId);

        url = url + "?params=" +encodeURIComponent(JSON.stringify({
          memberName:that.userInfo.nickName,
          groupId:data.groupId,
          schoolId: that.schoolId,
          receiveUserIds: (data.orderInfo!==undefined && data.orderInfo!=='')?data.orderInfo.memberIds:''
        }));

        console.log("websocketUrl", url)

        this.sockectClient = new WebSocket(url);

        this.sockectClient.onopen = function () {
          console.log("Socket 已打开");
          that.updateSocketState(true)

          // 如果是第一次且订单的话 发送卡片消息
          if (data.chatType === "ORDER" && (data.groupId === ''
              || data.groupId === undefined)) {
            if (data.orderInfo !== null && data.orderInfo !== undefined) {
              that.sendMsgForContent({
                "memberIds": data.orderInfo.memberIds,
                "orderNo": data.orderInfo.orderNo,
              }, 4);
            }
          }

          // 如果是第一次且是客服的话 发送问候消息
          if (data.chatType === "CUSTOMER" && (data.groupId === ''
              || data.groupId === undefined)) {
            that.sendMsgForContent('您好，有事咨询', 1);
          }
        }

        this.sockectClient.onmessage = function (msg) {
          let res = JSON.parse(msg.data);
          console.log("接收到消息", res);
          if (res.msgType === 1 || res.msgType === 4) {
            that.chatMsgList.push(res.content);
          } else if (res.msgType === 0) {
            that.chatMsgList = res.content;
          } else {
            that.updateSocketState(false);
            that.errorMsg = res.content
          }
          that.scrollBottom();
        }

        //关闭事件
        this.sockectClient.onclose = function () {
          console.log("Socket已关闭");
          that.updateSocketState(false);
          that.scrollBottom();
        };

        //发生了错误事件
        this.sockectClient.onerror = function () {
          console.log("Socket发生了错误");
          that.updateSocketState(false)
          that.scrollBottom();
        }
      }
    }

    // 点击发送消息
    , sendMsg() {
      if (this.chatInputMsg === '') {
        return;
      }
      this.sendMsgForContent(this.chatInputMsg);
      this.chatInputMsg = '';
    }
    , sendMsgForContent(msg, msgType) {
      let prams = {...this.msgTemplate};
      prams.message = msg;
      prams.msgType = msgType || 1;
      console.log("发送消息", prams);
      this.sockectClient.send(JSON.stringify(prams));
      this.scrollBottom();
    }
    , scrollBottom() {
      this.$nextTick(() => {
        this.scrollTop = 1000000 * (Math.floor(Math.random() * 100) + 1)
      });
    }
    , updateSocketState(state) {
      this.socketOpen = state;
      if (state) {
        this.socketStateMsg = '连接中';
      } else {
        this.socketStateMsg = '连接断开，点击重连';
      }
    }
  },
  onUnload() {
    // 当离开页面时销毁或清理数据
    if (this.sockectClient !== undefined && this.sockectClient !== null) {
      this.sockectClient.close();
    }
  },
}
